package com.leetcode.partition1;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/10/19 10:15
 */
public class LC34在排序数组中查找元素的第一个和最后一个位置 {

    public static int[] searchRange(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int[] answer = {-1, -1};
        boolean flag = false;
        //查找first
        while (left <= right) {
            if (left == right && nums[left] != target) break;
            int mid = (left + right) >>> 1;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            } else {
                if (mid - 1 >= 0 && nums[mid - 1] == target) {
                    right = mid - 1;
                } else {
                    answer[0] = mid;
                    flag = true;
                    break;
                }
            }
        }
        if (!flag) return answer;
        //查找last
        left = 0;
        right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) >>> 1;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            } else {
                if (mid + 1 <= nums.length - 1 && nums[mid + 1] == target) {
                    left = mid + 1;
                } else {
                    answer[1] = mid;
                    break;
                }
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 6;
        System.out.println(Arrays.toString(searchRange(nums, target)));
    }
}
